<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '学习列表',
    enablePullDownRefresh: false,
  },
}
</route>

<template>
  <view class="learn-container">
    <view
      class="h-full"
      :class="`current-tab-${tab + 1}`"
    >
      <wd-tabs
        v-model="tab"
        @change="changeTab"
        custom-class="learn-tabs"
      >
        <block
          v-for="(item, inx) in tabList"
          :key="inx"
        >
          <wd-tab :title="item.title">
            <scroll-view
              class="scroll-view h-full"
              scroll-y
              enable-back-to-top
              refresher-enabled
              :refresher-triggered="item.refresherTriggered"
              @refresherrefresh="onRefresherrefresh"
              @scrolltolower="onScrolltolower"
            >
              <template v-if="item.data.length > 0">
                <view class="learn-list">
                  <view
                    class="learn-item"
                    v-for="data in item.data"
                    :key="data.id"
                  >
                    <view class="learn-item-image common-image-corner">
                      <image
                        class="img"
                        :src="formatUrlString(data.coverUrl)[0]"
                        mode="aspectFill"
                      />
                    </view>
                    <view class="learn-item-info">
                      <view>
                        <view class="info-title ellipsis-2">
                          {{ data.name }}
                        </view>
                        <view class="info-desc">{{ data.type_dictText }}</view>
                        <view class="info-desc">
                          {{ data.resourceType_dictText }}
                        </view>
                      </view>
                      <view
                        class="learn-item-info__bottom"
                        :class="data.score ? 'has-date' : ''"
                      >
                        <view
                          class="info-desc"
                          v-if="data.score"
                        >
                          {{ data.score }}分
                        </view>
                        <view>
                          <wd-button
                            v-if="tab === 0"
                            size="small"
                            @click="goLearn(data)"
                          >
                            去学习
                          </wd-button>
                          <wd-button
                            v-else
                            size="small"
                            @click="goLearn(data)"
                          >
                            去复习
                          </wd-button>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
                <wd-loadmore
                  finished-text="没有更多了"
                  :state="tabList[inx].loadState"
                  @reload="getDataList"
                />
              </template>
              <wd-status-tip
                v-else
                image="content"
                tip="暂无内容"
              />
            </scroll-view>
          </wd-tab>
        </block>
      </wd-tabs>
    </view>
  </view>
</template>

<script setup>
import { uniNavigateTo, formatUrlString } from '@/utils'
import CourseApi from '@/service/course'

const tab = ref(0)

const tabList = ref([
  {
    title: '待学课程',
    data: [],
    pageNo: 1,
    pageSize: 10,
    loadState: 'loading',
    refresherTriggered: false,
    lessonUserStatus: 'notStarted',
  },
  {
    title: '已学课程',
    data: [],
    pageNo: 1,
    pageSize: 10,
    loadState: 'loading',
    refresherTriggered: false,
    lessonUserStatus: 'complete',
  },
])

const changeTab = ({ index }) => {
  console.log('changeTab', index, tab.value)
  nextTick(() => {
    console.log('changeTab-1', index, tab.value)
    getDataList()
  })
}

const getDataList = async () => {
  const inx = tab.value
  const data = tabList.value[inx]
  console.log('d', data, inx)
  if (data.loadState === 'finished') return
  try {
    const params = {
      pageNo: data.pageNo,
      pageSize: data.pageSize,
      lessonUserStatus: data.lessonUserStatus,
      order: 'desc',
      column: 'createTime',
    }
    const { code, result } = await CourseApi.getUserCourseLessonList(params)
    console.log('data', result)
    if (code === 200 && result) {
      const { records, pages } = result
      if (records?.length) {
        data.data = [...data.data, ...records]
      }
      if (data.pageNo < pages) {
        data.pageNo++
      } else {
        data.loadState = 'finished'
      }
    } else {
      data.loadState = 'error'
    }
  } catch (e) {
    data.loadState = 'error'
  }
}

const reset = () => {
  const inx = tab.value
  const data = tabList.value[inx]
  data.pageNo = 1
  data.data = []
  data.loadState = 'loading'
}

// 初始化
const init = async () => {
  tab.value = 0
  for (let i = 0; i < tabList.value.length; i++) {
    const data = tabList.value[i]
    data.pageNo = 1
    data.data = []
    data.loadState = 'loading'
  }

  try {
    await getDataList()
  } finally {
    isInit.value = false
  }
}

const onRefresherrefresh = async () => {
  tabList.value[tab.value].refresherTriggered = true
  // 重置分页数据，刷新接口
  reset()
  try {
    await getDataList()
  } finally {
    tabList.value[tab.value].refresherTriggered = false
  }
}

const onScrolltolower = () => {
  getDataList()
}

const isInit = ref(true)
onLoad(() => {
  init()

  uni.$on('updateLearn', (id) => {
    console.log('updateLearn', id)

    /**
     * 更好的体验是不刷新
     */
    // 执行全部刷新
    init()

    // 在未学习中找到此课程，并删除
    // const data = tabList.value[0].data
    // const inx = data.findIndex((v) => v.id === id)
    // // const currentData = data[inx]
    // if (inx > -1) {
    //   data.splice(inx, 1)
    // }

    // 在已学中加入一条
    // const data2 = tabList.value[1].data
    // data2.unshift({ ...currentData })

    // 已学习重刷
    // const data1 = tabList.value[1]
    // data1.pageNo = 1
    // data1.data = []
    // data1.loadState = 'loading'
  })
})

const goLearn = (data) => {
  if (tab.value === 0) {
    CourseApi.addUserCourse({
      lessonId: data.id,
    })
  }

  // uniNavigateTo(
  //   `/pages-sub/learn/detail/index?id=${data.id}&completeStatus=${tabList.value[tab.value].lessonUserStatus}`,
  // )
  uniNavigateTo(`/pages-sub/learn/detail/index?id=${data.id}`)
}

onShow(() => {
  console.log('isInit', isInit.value)
  // if (!isInit.value) {
  //   getDataList()
  // }
})
</script>

<style lang="scss" scoped>
.learn {
  &-container {
    position: fixed;
    inset: 0;
  }

  &-list {
    padding: 0 30rpx;
  }

  &-item {
    display: flex;
    height: 200rpx;
    min-height: 200rpx;
    margin-bottom: $uni-spacing-col-lg;

    .info-title {
      font-size: 24rpx;

      // margin-bottom: $uni-spacing-row-sm;
      // font-size: $uni-font-size-lg;
      font-weight: 600;
      line-height: 40rpx;
    }

    .info-desc {
      font-size: 22rpx;
      line-height: 31rpx;

      // font-size: $uni-font-size-base;
      color: $uni-text-color-grey;
    }

    &-image {
      flex: 2;
    }

    &-info {
      display: flex;
      flex: 3;
      flex-direction: column;
      justify-content: space-between;

      // padding-left: $uni-spacing-row-base;

      &__bottom {
        display: flex;
        align-items: center;
        justify-content: flex-end;

        &.has-date {
          justify-content: space-between;
        }
      }
    }
  }
}

:deep() {
  .learn-tabs {
    display: flex;
    flex-direction: column;
    height: 100%;

    .wd-tabs {
      &__container {
        flex: 1;
      }
    }

    .wd-tab {
      // height: 100%;

      &__body {
        height: 100%;
      }
    }
  }
}

@for $i from 1 through 2 {
  .current-tab-#{$i} {
    :deep() {
      .wd-tab {
        &:nth-child(#{$i}) {
          height: 100%;
        }
      }
    }
  }
}
</style>
